<template>
  <div class="Active">
    <div class="Active__top"><nuxt-link style="color: #333856;padding:8px;" to='/active/activeList'>返回</nuxt-link></div>
    <el-card shadow="never" class="Active__card">
      <el-form :model="form" ref="headerForm" label-width="100px" label-position="left" class="Active__form">
        <el-form-item
          prop="actName"
          :rules="[
            { required: true, message: '活动名称不能为空'}
          ]"
         label="活动名称">
         <el-input v-model="form.actName" style="width:194px;" size="mini" placeholder="单行输入"></el-input>
        </el-form-item>
        <el-form-item
          prop="actType"
          :rules="[
            { required: true, message: '活动类型不能为空'}
          ]"
         label="活动类型">
          <el-select v-model="form.actType" style="width:194px;" size="mini" placeholder="选择活动类型">
            <el-option label="换购活动" :value="1"> </el-option>
            <el-option label="满赠活动" :value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="startTime"
          :rules="[
            { required: true, message: '请设置开始时间'}
          ]"
        >
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form.startTime"
          style="width:194px;" size="mini" type="datetime" placeholder="设置开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="结束时间"
          prop="endTime"
          :rules="[
            { required: true, message: '请设置结束时间'}
          ]"
        >
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form.endTime"
          style="width:194px;" size="mini" type="datetime" placeholder="设置结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="活动描述"
          prop="actDesc"
          :rules="[
            { required: true, message: '请输入活动描述'}
          ]"
        >
        <el-input type="textarea" v-model="form.actDesc" style="width:194px;" size="mini" placeholder="多行输入"></el-input>
        </el-form-item>
      </el-form>
      <el-form label-width="100px" label-position="left" class="Active__form__right">
        <el-form-item
          prop="activityUrl"
          :rules="[
            { required: true, message: '轮播图片不能为空'}
          ]"
         label="轮播图片">
         <ecp-upload title="点击上传活动图片" :isError="form.activityUrlError" v-model="form.activityUrl"/>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="Active__card" style="background-color:#fff;margin-top:15px;" v-for="(active, index) in favourableActivityList" :key="index">
      <div class="el-card__body" style="border-bottom:1px solid #bdbdbd;">
        <button class="Ecp-button-primary" style="float:right;" @click="showGoodsDialog(index)">添加商品</button>
        <div class="Active__form__group">
          <div class="Active__form__label">目标金额</div>
          <div class="Active__form__content">
            <el-input size="mini" v-model.number="active.targetAmount" type="number" placeholder="单行输入"></el-input>
          </div>
        </div>
        <div class="Active__form__group" v-show="active.targetAmountError">
          <div class="Active__form__label" style="color:#f00;">目标金额不能为空</div>
        </div>
      </div>
      <div class="Active__check">
        <div class="Active__check__card" v-for="(item, key) in active.goodsActivityList" :key="key">
          <div class="Active__check__card__top">
            <el-checkbox @change="val => deleteSelectionChange(val, item, index)" :value="active.selectedGoodsId.indexOf(item.goodsId)>-1">
              <img class="Active__check__card__img" :src="item.goodsImg"/>
            </el-checkbox>
            <div class="Active__check__card__right">
              <p>{{item.goodsName}}</p>
              <p>{{item.goodsSn}}</p>
              <p style="margin-top:23px;">ID:{{item.goodsId}}</p>
            </div>
          </div>
          <div style="padding-left:45px;">
            <div class="Active__check__form__group">
              <div class="Active__check__form__label">换购价格</div>
              <div class="Active__check__form__content">
                <el-input v-model.number="item.discountPrice" type="number" size="mini" placeholder="单行输入"></el-input>
              </div>
            </div>
            <div class="Active__check__form__group">
              <div class="Active__check__form__label">商品数量</div>
              <div class="Active__check__form__content">
                <el-input v-model.number="item.actGoodsCount" type="number" size="mini" placeholder="单行输入"></el-input>
              </div>
            </div>
          </div>
        </div>
        <div :class="{'text-error': active.goodsActivityListError}" v-if="active.goodsActivityList.length==0">{{active.goodsActivityListError?'活动商品列表不能为空':'暂无活动商品'}}</div>
      </div>
      <div style="padding:20px 20px 0;height:50px;" v-if="active.goodsActivityList.length==0">
        <button class="Ecp-button-primary" style="float:right;" @click="favourableActivityList.splice(index, 1)">删除此项</button>
      </div>
    </div>
    <div class="active-btns">
      <p><span @click="addActiveType" style="padding:10px 0;cursor: pointer;">添加目标金额</span></p>
      <button class="Ecp-button-primary" @click="saveActive">保存</button>
      <!-- <button style="margin-left:124px;" class="Ecp-button-primary">开始活动</button> -->
    </div>
    <!-- 商品列表弹窗 -->
    <el-dialog
      class="Active__dialog"
      :visible.sync="dialog.show"
      top="50px"
      width="800px">
      <div slot="title">
        <div style="margin-top:10px;">
          <button class="Ecp-button-primary" style="float:right;margin-right:30px;" @click="doSearchGoods">搜索</button>
          <div class="Active__form__group">
            <div class="Active__form__label">商品名称</div>
            <div class="Active__form__content">
              <el-input size="mini" v-model="dialog.goodsName" placeholder="单行输入"></el-input>
            </div>
          </div>
          <div class="Active__form__group" style="margin-right:8px;">
            <div class="Active__form__label">价格</div>
            <div class="Active__form__content" style="margin-left:50px;">
              <el-input size="mini" v-model="dialog.startPrice" placeholder="单行输入"></el-input>
            </div>
          </div>
          <div class="Active__form__group">
            <div class="Active__form__label">到</div>
            <div class="Active__form__content" style="margin-left:26px;">
              <el-input v-model="dialog.endPrice" size="mini" placeholder="单行输入"></el-input>
            </div>
          </div>
          <div class="Active__form__group">
            <div class="Active__form__label">商品分类</div>
            <div class="Active__form__content">
              <el-cascader expand-trigger="hover" change-on-select :props="shopProps"
              :options="shopSort" v-model="dialog.selectedShopSort" placeholder="选择分类" clearable>
              </el-cascader>
            </div>
          </div>
        </div>
      </div>
      <el-table :data="goodsList" height="400px" style="width: 100%"
        @selection-change="handleSelectionChange">
          <!-- <el-table-column type="selection" width="55">
          </el-table-column> -->
          <el-table-column label="选择" width="55">
            <template slot-scope="scope">
              <el-checkbox @change="val => handleSelectionChange(val, scope.row)" :value="dialog.selectedGoodsId.indexOf(scope.row.id)>-1" />
            </template>
          </el-table-column>
          <el-table-column label="商品" width="200">
              <div class="Active__table__card" slot-scope="scope">
                <img class="Active__table__card__img" :src="scope.row.goodsImg" alt="">
                <div class="Active__table__card__right">
                  <p class="Active__table__card__name">{{scope.row.goodsName}}</p>
                  <p class="Active__table__card__id">商品ID：{{scope.row.id}}</p>
                </div>
              </div>
          </el-table-column>
          <el-table-column prop="shopPrice" label="价格">
          </el-table-column>
          <el-table-column prop="goodsNumber" label="库存">
          </el-table-column>
          <el-table-column prop="sales" label="销量">
          </el-table-column>
          <el-table-column prop="addTime" label="上架时间">
          </el-table-column>
      </el-table>
      <el-pagination
        small
        v-show="pageData.total>0"
        @current-change="getGoodsList"
        :current-page="pageData.pageNum"
        :page-size="pageData.pageSize"
        layout="prev, pager, next"
        :total="pageData.total">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialog.show = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveSelectionChange">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import SetAvatar from '~/components/setAvatar'
import EcpUpload from '~/components/ecpUpload'
import { getShopCategoryList, } from '~/api/'
import {addFavourable, findGoodsList, findFavourableForm, updateFavourable} from '~/api/apiv1'
import { searchOption } from "~/utils/"
import testImg from '~/static/images/de.png'
  export default{
    components:{
      SetAvatar,
      EcpUpload
    },
    async asyncData({app}) {
      try {
        const [res1, res2] = await Promise.all([findGoodsList(app), getShopCategoryList(app)])
        if (res1.code == '0' && res2.code == '0') {
          const { pageNum, pageSize, total, totalNum, list } = res1.data.page
          return {
            goodsList: list,
            shopSort: searchOption(res2.data.tree),
            pageData: { pageNum, pageSize, total, totalNum }
          }
        }else {
          return {
            goodsList: [],
            shopSort: [],
            pageData: {
              pageNum: 1,
              pageSize: 15,
              total: 0,
              totalNum: 1
            },
            message: res1.message == 'Success' ? res2.message : res1.message
          }
        }
      } catch (error) {
        console.error(`获取商品列表接口错误，错误信息${error}`)
      }
    },
    data() {
      return {
        shopProps: {
          value: 'id',
          children: 'childList',
          label: 'name'
        },
        favourableActivityList: [
          {
            targetAmount: '',
            targetAmountError: false,
            goodsActivityListError: false,
            selectedGoodsId: [],
            goodsActivityList: []
          }
        ],
        dialog:{
          show: false,
          goodsName: '',
          startPrice: '',
          endPrice: '',
          shopProps: '',
          index: 0,
          selectedShopSort: [],
          selectedGoodsId: [],
          goodsActivityList: []
        },
        form: {
          actName: '',
          actType: 1,
          startTime: '',
          endTime: '',
          activityUrl: '',
          actDesc: '',
          activityUrlError: false,
          favourableActivityList: []
        }
      }
    },
    async beforeMount() {
      // 编辑活动信息
      if (this.$route.params.id != 0 ) {
        const res = await findFavourableForm(this, this.$route.params.id)
        if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})
        const {actName, actType, startTime, endTime, activityUrl, actDesc, favourableActivityList} = res.data.favourableInfoVo
        this.form = {actName, actType, startTime, endTime, activityUrl, actDesc, favourableActivityList,activityUrlError: false}
        this.favourableActivityList = []
        favourableActivityList.map(item => {
          let favourable = {
            targetAmount: item.targetAmount,
            targetAmountError: false,
            goodsActivityListError: false,
            selectedGoodsId: [],
            goodsActivityList: []
          }
          item.goodsActivityList.map(data => {
            favourable.selectedGoodsId.push(data.id)
            favourable.goodsActivityList.push({
              "goodsImg": data.goodsImg,
              "goodsId": data.id,
              "goodsSn": data.goodsSn,
              "goodsName": data.goodsName,
              "actGoodsCount": data.actGoodsCount,
              "discountPrice": data.discountPrice
            })
          })
          this.favourableActivityList.push(favourable)
        })
      }
    },
    methods: {
      showGoodsDialog(index) {
        // 打开商品列表弹层
        this.dialog.index = index
        this.dialog.show = true
        this.dialog.goodsActivityList = this.favourableActivityList[index].goodsActivityList
        this.dialog.selectedGoodsId = this.favourableActivityList[index].selectedGoodsId
        // this.favourableActivityList[index].goodsActivityList.map(item=>this.dialog.selectedGoodsId.push(item.goodsId))
      },
      handleSelectionChange(val, data) {
        // 勾选商品事件
        // console.log(val, data)
        if (val) {
          this.dialog.selectedGoodsId.push(data.id)
          this.dialog.goodsActivityList.push({
            "goodsImg": data.goodsImg,
            "goodsId": data.id,
            "goodsSn": data.goodsSn,
            "goodsName": data.goodsName,
            "actGoodsCount": '',
            "discountPrice": ""
          })
        } else {
          const index = this.dialog.selectedGoodsId.indexOf(data.id)
          this.dialog.selectedGoodsId.splice(index, 1)
          this.dialog.goodsActivityList.splice(index, 1)
        }
      },
      deleteSelectionChange(val, data, index) {
        // 删除已选商品
        // console.log(val, data)
        if (val) return
        const key = this.dialog.selectedGoodsId.indexOf(data.goodsId)
        this.favourableActivityList[index].selectedGoodsId.splice(key, 1)
        this.favourableActivityList[index].goodsActivityList.splice(key, 1)
      },
      saveSelectionChange() {
        // 将选择的商品列表添加到表单商品列表
        const index = this.dialog.index
        this.favourableActivityList[index].selectedGoodsId = this.dialog.selectedGoodsId
        this.favourableActivityList[index].goodsActivityList = this.dialog.goodsActivityList
        this.dialog.show = false
      },
      addActiveType() {
        this.favourableActivityList.push({
          targetAmount: '',
          targetAmountError: false,
          goodsActivityListError: false,
          selectedGoodsId: [],
          goodsActivityList: []
        })
      },
      doSearchGoods() {
        const selectedShopSort = this.dialog.selectedShopSort
        this.dialog.shopProps = selectedShopSort[selectedShopSort.length-1]
        this.getGoodsList(1)
      },
      async getGoodsList(page) {
        // 商品列表翻页
          const res = await findGoodsList(this,this.dialog.goodsName,this.dialog.startPrice,this.dialog.endPrice,'','',this.dialog.shopProps,'', page, 15, 'addTime', 2)
          if (res.code === '0') {
            const { pageNum, pageSize, total, totalNum, list } = res.data.page
            this.goodsList = list
            this.pageData = {pageNum, pageSize, total, totalNum}
          } else {
              this.$message.error(res.message)
          }
      },
      checkFavourableActivityList () {
        let error = true;
        let list = []
        this.favourableActivityList.map(item => {
          item.targetAmountError = item.targetAmount==''?true:false
          item.goodsActivityListError = item.goodsActivityList.length==0?true:false
          if (item.targetAmountError||item.goodsActivityListError) return error = false
          let goods = []
          item.goodsActivityList.map(data => {
            goods.push({
              "goodsId": data.goodsId,
              "goodsSn": data.goodsSn,
              "goodsName": data.goodsName,
              "actGoodsCount": data.actGoodsCount,
              "discountPrice": data.discountPrice
            })
          })
          list.push({
            targetAmount:item.targetAmount,
            goodsActivityList:goods
          })
        })
        return error&&list
      },
      saveActive() {
        this.$refs['headerForm'].validate(async (result) => {
          if (this.form.activityUrl=='') return this.form.activityUrlError = true
          if (!result) return
          const listCheck = this.checkFavourableActivityList()
          if (!listCheck) return this.$alert('目标金额或商品列表不能为空', "提示", {type: 'error'})
          // const favourableActivityList = JSON.stringify(listCheck)
          const favourableActivityList = listCheck
          const {actName,actType,startTime,endTime,actDesc,activityUrl} = this.form
          let res;
          if (this.$route.params.id == 0) {
            res = await addFavourable(this, {actName,actType,startTime,endTime,actDesc,activityUrl,favourableActivityList})
          } else {
            res = await updateFavourable(this, {id: this.$route.params.id, actName,actType,startTime,endTime,actDesc,activityUrl,favourableActivityList})
          }
          if (res.code != '0') return this.$alert(res.message, "提示", {type: 'error'})
          this.$message.success('保存成功')
          this.$router.replace("/active/activeList")
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
.text-error {
  color: #f00;
}
.Active{
    padding: 0px 30px 50px;
    background: #f3f3f3;
    &__dialog {
      & /deep/ {
        .el-pagination {
          text-align: center;
        }
        .el-dialog__body {
          padding: 0;
        }
      }
    }
    &__table {
      &__card {
        position: relative;
        text-align: left;
        margin-bottom: 40px;
        &__img {
          float: left;
          width: 54px;
          height: 83px;
        }
        &__right {
          margin-left: 70px;
        }
        &__name {
          font-size: 16px;
          line-height: 16px;
          height: 40px;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          word-break: break-all;
        }
        &__shop {
          font-size: 16px;
        }
        &__id {
          font-size: 12px;
          line-height: 20px;
        }
      }
    }
    &__check {
      padding: 20px 40px 0;
      overflow: hidden;
      &__form {
        &__group {
          line-height: 25px;
          margin-top: 13px;
        }
        &__label {
          float: left
        }
        &__content {
          margin-left: 83px;
          & /deep/ {
            .el-input__inner, .el-input--suffix{
              border-radius: 9px;
              line-height: 25px;
              height: 25px;
            }
          }
        }
      }
      &__card {
        width: 290px;
        float: left;
        // margin-left: 100px;
        margin-bottom: 50px;
        &:nth-child(3n),&:nth-child(3n+2) {
          margin-left: 21px;
        }
        // &:nth-child(4n) {
        //   // margin-left: 210px;
        //   margin-top: 40px;
        // }
        &__right {
          margin-left:125px;
          height:83px;
          p {
            line-height: 18px;
            font-size: 16px;
          }
        }
        &__img {
          vertical-align: middle;
          height: 83px;
          width: 54px;
        }
        & /deep/ {
          .el-checkbox {
            float: left;
          }
          .el-checkbox__input {
            vertical-align: top;
            margin-top: 28px;
          }
          .el-checkbox__inner {
            border-color: #999;
          }
          .el-checkbox__label {
            padding-left: 31px;
          }
        }
      }
    }
    &__form {
      display: inline-block;
      width: 430px;
      &__label{
        float: left;
      }
      &__content {
        margin-left: 80px;
      }
      &__group{
        line-height: 30px;
        display: inline-block;
        vertical-align: middle;
        &:not(:last-child) {
          margin-right: 40px;
        }
        & /deep/ {
          .el-input__icon, .el-cascader {
            line-height: 26px;
          }
          .el-input__inner, .el-input--suffix{
            height: 26px;
            line-height: 26px;
            border-radius: 9px;
            background-color: #f0f5fb;
            border: none;
            text-align: center;
            width: 128px;
          }
        }
      }
    & /deep/ {
      .el-input__icon {
        line-height: 26px;
      }
      .el-input__inner, .el-input--suffix{
        height: 26px;
        line-height: 26px;
        border-radius: 9px;
        background-color: #f0f5fb;
        border: none;
      }
      .el-textarea__inner {
        border-radius: 9px;
        background-color: #f0f5fb;
        border: none;
      }
      .el-form-item__label {
        line-height: 26px;
        font-size: 16px;
        color: #191919;
      }
      .el-form-item__content {
        line-height: 26px;
      }
    }
    &__right {
      display: inline-block;
      vertical-align: top;
      & /deep/ {
        .el-form-item__label {
          line-height: 26px;
          font-size: 16px;
          color: #191919;
        }
        .Upload .el-upload--picture-card {
          width: 360px;
          height: 142px;
          line-height: 142px;
        }
      }
    }
  }
  &__card {
    padding-bottom: 20px;
    & /deep/ {
      .el-card__body {
        padding-left: 50px;
        position: relative;
        &::before{
          content: "";
          display: block;
          width: 6px;
          height: 6px;
          border-radius: 50%;
          background-color: #333856;
          position: absolute;
          top: 32px;
          left: 30px;
        }
      }
    }
  }
    &__top {
      text-align: right;
      line-height: 50px;
    }
 .active-btns{
   margin-top: 15px;
   text-align: center;
    p{
      text-align: left;
      line-height: 26px;
      font-size: 16px;
      color: #606266;
       }
    .Ecp-button-primary {
      height:40px;
      width:120px;
      fonts-size:18px;
      border-radius:20px;
    }
 }
}
</style>

